<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 7.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="7.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="7.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#7">Chapter 7. Iterators and the Generic <b>for</b></a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>7.2 &ndash; The Semantics of the Generic <b>for</b></h2>

<p>One drawback of those previous iterators is that we need
to create a new closure for each new loop.
For most situations, this is not a real problem.
For instance, in the <code>allwords</code> iterator,
the cost of creating one single closure is negligible compared
to the cost of reading a whole file.
However, in a few situations this overhead can be undesirable.
In such cases, we can use the generic <b>for</b> itself
to keep the iteration state.

<p>We saw that the generic <b>for</b> keeps the iterator
function internally, during the loop.
Actually, it keeps three values:
The iterator function, an <em>invariant state</em>,
and a <em>control variable</em>.
Let us see the details now.

<p>The syntax for the generic <b>for</b> is as follows:
<pre>
    for &lt;var-list> in &lt;exp-list> do
      &lt;body>
    end
</pre>
where <code>&lt;var-list></code> is a list of one or more variable names,
separated by commas,
and <code>&lt;exp-list></code> is a list of one or more expressions,
also separated by commas.
More often than not, the expression list has only one element,
a call to an iterator factory.
For instance, in the code
<pre>
    for k, v in pairs(t) do
      print(k, v)
    end
</pre>
the list of variables is <code>k, v</code>;
the list of expressions has the single element <code>pairs(t)</code>.
Often the list of variables has only one variable too, as in
<pre>
    for line in io.lines() do
      io.write(line, '\n')
    end
</pre>
We call the first variable in the list the <em>control variable</em>.
Its value is never <B>nil</B> during the loop,
because when it becomes <B>nil</B> the loop ends.

<p>The first thing the <b>for</b> does is to evaluate the
expressions after the <b>in</b>.
These expressions should result in the three values
kept by the <b>for</b>:
the iterator function, the invariant state,
and the initial value for the control variable.
Like in a multiple assignment,
only the last (or the only) element of the list
can result in more than one value;
and the number of values is adjusted to three,
extra values being discarded or <B>nil</B>s added as needed.
(When we use simple iterators,
the factory returns only the iterator function,
so the invariant state and the control variable get <B>nil</B>.)

<p>After this initialization step,
the <b>for</b> calls the iterator function with two arguments:
the invariant state and the control variable.
(Notice that, for the <b>for</b> structure,
the invariant state has no meaning at all.
It only gets this value from the initialization step and
passes it when it calls the iterator function.)
Then the <b>for</b> assigns the values returned by the iterator
function to variables declared by its variable list.
If the first value returned
(the one assigned to the control variable) is nil,
the loop terminates.
Otherwise, the <b>for</b> executes its body
and calls the iteration function again,
repeating the process.

<p>More precisely,
a construction like
<pre>
    for var_1, ..., var_n in explist do block end
</pre>
is equivalent to the following code:
<pre>
    do
      local _f, _s, _var = explist
      while true do
        local var_1, ... , var_n = _f(_s, _var)
        _var = var_1
        if _var == nil then break end
        block
      end
    end
</pre>
So,
if our iterator function is <em>f</em>,
the invariant state is <em>s</em>,
and the initial value for the control variable is <em>a<SUB>0</SUB></em>,
the control variable will loop over the values
<em>a<SUB>1</SUB> = f(s, a<SUB>0</SUB>)</em>,
<em>a<SUB>2</SUB> = f(s, a<SUB>1</SUB>)</em>,
and so on, until <em>a<SUB>i</SUB></em> is <B>nil</B>.
If the <b>for</b> has other variables,
they simply get the extra values returned
by each call to <code>f</code>.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="7.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

